package com.hang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.config.RedisConfig;
import com.hang.entity.*;
import com.hang.exception.MyException;
import com.hang.exception.MyExceptionEnum;
import com.hang.mapper.*;
import com.hang.mapstruct.ItemMapStruct;
import com.hang.mapstruct.UserMapStruct;
import com.hang.model.dto.base.ConditionDTO;
import com.hang.model.dto.request.ItemModelDTO;
import com.hang.model.dto.request.ItemQueryDTO;
import com.hang.model.dto.request.PersonalStaticsDTO;
import com.hang.model.dto.response.ItemApplyInfoVO;
import com.hang.model.dto.response.ItemInfoModel;
import com.hang.model.dto.response.ItemQueryListVO;
import com.hang.model.dto.response.PersonalTaskVO;
import com.hang.model.vo.ItemInfoDetailModel;
import com.hang.model.vo.UserInfoVO;
import com.hang.service.IItemService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 */
@Service
@AllArgsConstructor
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item>
    implements IItemService{
    private RedisConfig redisConfig;

    private ItemMapStruct itemMapStruct;

    private ModuleMapper moduleMapper;

    private ItemUserMapper itemUserMapper;

    private TbDocumentMapper documentMapper;

    private TbFileMapper fileMapper;

    private TaskMapper taskMapper;

    private BugMapper bugMapper;

    private UserMapper userMapper;

    private UserMapStruct userMapStruct;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createItem(ItemModelDTO itemModelDTO) {
        if(ObjectUtil.isEmpty(itemModelDTO)){
            throw new MyException(MyExceptionEnum.OBJECT_IS_NULL);
        }

        //先创建出这个项目
        Item item = itemMapStruct.itemModelDTOToItem(itemModelDTO);

        this.baseMapper.insert(item);

        //需要将项目管理者直接添加进项目用户表
        ItemUser itemUser = new ItemUser();
        itemUser.setItemId(item.getItemId());
        itemUser.setItemName(item.getItemName());
        itemUser.setUserId(itemModelDTO.getManagerId());
        itemUser.setRealName(itemModelDTO.getManagerName());

        itemUserMapper.insert(itemUser);

        //redis加入
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(3);
        redisTemplate.opsForSet().add(String.valueOf(itemUser.getUserId()),item.getItemId());

        //更新操作
        packageItemRedis(item);
    }

    /**
     * 编辑项目
     * @param itemModelDTO
     */
    @Override
    public void editItem(ItemModelDTO itemModelDTO) {
        Long itemId = itemModelDTO.getItemId();

        if(ObjectUtil.isEmpty(itemId) || ObjectUtil.isEmpty(itemModelDTO)){
            throw new MyException(MyExceptionEnum.OBJECT_IS_NULL);
        }

        Item dbItem = this.baseMapper.selectById(itemId);
        if(ObjectUtil.isEmpty(dbItem)){
            throw new MyException(MyExceptionEnum.DATA_DOES_NOT_EXIST);
        }

        //修改
        BeanUtils.copyProperties(itemModelDTO,dbItem);

        //存储
        this.baseMapper.updateById(dbItem);
    }

    /**
     * 删除项目：如果项目下还有模块，则不允许删除
     * @param itemId
     */
    @Override
    public void deleteItem(Long itemId) {
        if(ObjectUtil.isEmpty(itemId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        //检查是否有模块属于这个项目
        QueryWrapper<Module> moduleQueryWrapper = new QueryWrapper<>();
        moduleQueryWrapper.lambda().eq(Module::getItemId,itemId);

        Integer count = moduleMapper.selectCount(moduleQueryWrapper);
        if(count > 0){
            throw new MyException(MyExceptionEnum.MODULE_HAS_DATA);
        }

        Item dbItem = this.baseMapper.selectById(itemId);
        if(ObjectUtil.isEmpty(dbItem)){
            throw new MyException(MyExceptionEnum.DATA_DOES_NOT_EXIST);
        }

        //进行逻辑删除
        this.baseMapper.deleteById(dbItem);
    }

    /**
     * 按条件搜索所有的项目列表，带分页
     * @param conditionDTO
     * @return
     */
    @Override
    public ItemQueryListVO getItemsByCondition(ConditionDTO conditionDTO) {
        if(ObjectUtil.isEmpty(conditionDTO)){
            throw new MyException(MyExceptionEnum.OBJECT_IS_NULL);
        }

        ItemQueryListVO itemQueryListVO = new ItemQueryListVO();

        //搜索条件
        String condition = conditionDTO.getConditionName();

        long number = -1L;
        //判断是不是纯数字，能不能转换成Long
        if(StrUtil.isNotBlank(condition) && checkIsNumber(condition)){
            number = Long.parseLong(condition);
        }

        //若按照ID的话，则是精准搜索
        if(number != -1L){
            Item item = Optional.ofNullable(this.baseMapper.selectById(number)).orElse(null);

            if(ObjectUtil.isNotEmpty(item)){
                itemQueryListVO.setTotal(1);
                itemQueryListVO.setItemInfoModelList(Collections.singletonList(itemMapStruct.itemToItemInfoModel(item)));
                return itemQueryListVO;
            }
        }

        //否则按照条件模糊搜索
        QueryWrapper<Item> itemQueryWrapper= new QueryWrapper<>();
        if(StrUtil.isNotBlank(condition)){
            itemQueryWrapper
                    .lambda()
                    .like(Item::getItemName,condition)
                    .or()
                    .like(Item::getManagerName,condition)
                    .or()
                    .like(Item::getCreateBy,condition);
        }

        //获取分页信息
        Integer pageNum = conditionDTO.getPageNum();
        Integer pageSize = conditionDTO.getPageSize();

        Page<Item> page = new Page<>(pageNum,pageSize);
        IPage<Item> iPage = this.baseMapper.selectPage(page,itemQueryWrapper);

        List<Item> records = Optional.ofNullable(iPage.getRecords()).orElse(new LinkedList<>());

        List<ItemInfoModel> itemInfoModelList = itemMapStruct.itemListToItemInfoModelList(records);

        itemQueryListVO.setTotal(this.baseMapper.selectCount(itemQueryWrapper));
        itemQueryListVO.setItemInfoModelList(itemInfoModelList);
        return itemQueryListVO;
    }

    /**
     * 获取项目详情
     * @param itemId
     * @return
     */
    @Override
    public ItemInfoDetailModel getItemDetailByItemId(Long itemId) {
        if(ObjectUtil.isEmpty(itemId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        Item dbItem = Optional.ofNullable(this.baseMapper.selectById(itemId)).orElse(null);

        if(ObjectUtil.isEmpty(dbItem)){
            throw new MyException(MyExceptionEnum.DATA_DOES_NOT_EXIST);
        }

        //查询基础数据
        ItemInfoDetailModel itemInfoDetailModel = itemMapStruct.itemToItemInfoDetailModel(dbItem);

        //查询模块相关数据
        QueryWrapper<Module> moduleQueryWrapper = new QueryWrapper<>();
        moduleQueryWrapper.lambda().eq(Module::getItemId,itemId);

        //查询项目模块数目(点击模块数目可以查看模块列表)
        Integer moduleCounts = Optional.ofNullable(moduleMapper.selectCount(moduleQueryWrapper)).orElse(0);
        List<Long> moduleIds = Optional.ofNullable(moduleMapper.selectList(moduleQueryWrapper)).orElse(new LinkedList<>()).stream().map(Module::getModuleId).collect(Collectors.toList());

        itemInfoDetailModel.setModuleCount(moduleCounts);

        //查询项目成员个数(点击成员数目可以查看成员列表)
        QueryWrapper<ItemUser> itemUserQueryWrapper = new QueryWrapper<>();
        itemUserQueryWrapper.lambda().eq(ItemUser::getItemId,itemId);
        Integer memberCount = Optional.ofNullable(itemUserMapper.selectCount(itemUserQueryWrapper)).orElse(0);
        itemInfoDetailModel.setMemberCount(memberCount);

        if(CollectionUtil.isNotEmpty(moduleIds)){
            //查询项目文档数目(点击查看文档列表)
            QueryWrapper<TbDocument> documentQueryWrapper = new QueryWrapper<>();
            documentQueryWrapper.lambda().in(TbDocument::getModuleId,moduleIds);
            Integer documentCount = Optional.ofNullable(documentMapper.selectCount(documentQueryWrapper)).orElse(0);
            itemInfoDetailModel.setDocumentCount(documentCount);

            //查询项目的文件数目(点击查看文件列表)
            QueryWrapper<TbFile> fileQueryWrapper = new QueryWrapper<>();
            fileQueryWrapper.lambda().in(TbFile::getModuleId,moduleIds);
            Integer fileCount = Optional.ofNullable(fileMapper.selectCount(fileQueryWrapper)).orElse(0);
            itemInfoDetailModel.setFileCount(fileCount);
        }else {
            itemInfoDetailModel.setDocumentCount(0);
            itemInfoDetailModel.setFileCount(0);
        }



        //查询项目的任务数目
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.lambda().eq(Task::getItemId,itemId);
        Integer taskCount = Optional.ofNullable(taskMapper.selectCount(taskQueryWrapper)).orElse(0);
        itemInfoDetailModel.setTaskCount(taskCount);

        //查询项目的故障数目
        QueryWrapper<Bug> bugQueryWrapper = new QueryWrapper<>();
        bugQueryWrapper.lambda().eq(Bug::getItemId,itemId);
        Integer bugCount = Optional.ofNullable(bugMapper.selectCount(bugQueryWrapper)).orElse(0);
        itemInfoDetailModel.setBugCount(bugCount);

        //扩展字段的数目查询
        for (int i = 1; i <= 6; i++) {
            packageItemDetail(itemId,itemInfoDetailModel,i);
        }

        return itemInfoDetailModel;
    }

    /**
     * 查看用户的项目空间列表
     *
     * @param itemQueryDTO
     * @return
     */
    @Override
    public ItemQueryListVO getMyItemsByCondition(ItemQueryDTO itemQueryDTO) {
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(3);

        Long userId = itemQueryDTO.getUserId();
        Integer itemType = itemQueryDTO.getItemType();
        String condition = itemQueryDTO.getCondition();

        Integer pageNum = itemQueryDTO.getPageNum();
        Integer pageSize = itemQueryDTO.getPageSize();

        ItemQueryListVO itemQueryListVO = new ItemQueryListVO();

        //获取用户对应的用户名
        if(1 == itemType){ //查找我加入的项目

            //先去redis中查看这个用户对应的项目数据列表
            Set<Object> items = redisTemplate.opsForSet().members(String.valueOf(userId));

            if(items!=null && CollectionUtil.isNotEmpty(items)){
                List<Long> itemIds = items.stream().map(
                        item -> {
                            String str = String.valueOf(item);
                            return Long.valueOf(str);
                        }
                ).collect(Collectors.toList());

                //获取项目信息列表并且转为视图
                List<ItemInfoModel> itemInfoModelList = itemMapStruct.itemListToItemInfoModelList(getItemListInfoByItemIds(itemIds));
                return packageData(itemInfoModelList,condition,pageNum,pageSize);
            }

            //如果在redis中没有找到，那么先去数据库中找，找到加载，没有找到则跳出程序
            QueryWrapper<ItemUser> itemUserQueryWrapper = new QueryWrapper<>();
            itemUserQueryWrapper.lambda().eq(ItemUser::getUserId,userId);

            List<Long> itemIds = Optional.ofNullable(itemUserMapper.selectList(itemUserQueryWrapper)).orElse(new LinkedList<>()).stream().map(ItemUser::getItemId).collect(Collectors.toList());

            //获取项目信息列表并且转为视图
            List<ItemInfoModel> itemInfoModelList = itemMapStruct.itemListToItemInfoModelList(getItemListInfoByItemIds(itemIds));

            itemIds.forEach(
                    itemId ->{
                        //先加载进redis
                        redisTemplate.opsForSet().add(String.valueOf(userId),itemId);
                    }
            );

            //再将视图展现
            return packageData(itemInfoModelList,condition,pageNum,pageSize);
        }else if(2 == itemType){    //查找我我管理的项目
            QueryWrapper<ItemUser> itemUserQueryWrapper = new QueryWrapper<>();
            itemUserQueryWrapper.lambda().eq(ItemUser::getUserId,userId);

            List<Long> itemIds = Optional.ofNullable(itemUserMapper.selectList(itemUserQueryWrapper)).orElse(new LinkedList<>()).stream().map(ItemUser::getItemId).collect(Collectors.toList());

            //条件筛选，我管理的，且我在项目中
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper
                    .lambda()
                    .eq(Item::getManagerId,userId)
                    .in(!itemIds.isEmpty(),Item::getItemId,itemIds);

            if(StrUtil.isNotBlank(condition)){
                itemQueryWrapper
                        .lambda()
                        .like(Item::getItemName,condition)
                        .or()
                        .like(Item::getCreateBy,condition)
                        .or()
                        .like(Item::getManagerName,condition);
            }

            //分页，转换
            Page<Item> page = new Page<>(pageNum,pageSize);
            List<Item> itemList = Optional.ofNullable(this.baseMapper.selectPage(page, itemQueryWrapper).getRecords()).orElse(new LinkedList<>());

            List<ItemInfoModel> itemInfoModelList = itemMapStruct.itemListToItemInfoModelList(itemList);

            itemQueryListVO.setTotal(this.baseMapper.selectCount(itemQueryWrapper));
            itemQueryListVO.setItemInfoModelList(itemInfoModelList);

            return itemQueryListVO;
        }else if(3 == itemType){    //查找企业项目列表(未加入的)
            /**
             * 先找出所有的项目列表，再与自己的项目作差集
             *
            */

            //先去redis中查看这个用户对应的项目数据列表
            Set<Object> items = redisTemplate.opsForSet().members(String.valueOf(userId));
            List<Long> itemIds = null;
            if(items!=null && CollectionUtil.isNotEmpty(items)){
                 itemIds = items.stream().map(
                        item ->{
                            String str = String.valueOf(item);
                            return Long.valueOf(str);
                        }
                ).collect(Collectors.toList());
            }else {
                //如果在redis中没有找到，那么先去数据库中找，找到加载，没有找到则跳出程序
                QueryWrapper<ItemUser> itemUserQueryWrapper = new QueryWrapper<>();
                itemUserQueryWrapper.lambda().eq(ItemUser::getUserId,userId);
                itemIds = Optional.ofNullable(itemUserMapper.selectList(itemUserQueryWrapper)).orElse(new LinkedList<>()).stream().map(ItemUser::getItemId).collect(Collectors.toList());
            }

            //查询出所有的项目id列表
            List<Long> allItemIds = Optional.ofNullable(this.baseMapper.selectList(null)).orElse(new LinkedList<>()).stream().map(Item::getItemId).collect(Collectors.toList());

            //查找出它们的差集元素
            List<Long> finalItemIds = itemIds;
            List<Long> targetItemIds = allItemIds.stream().filter(item -> !finalItemIds.contains(item)).collect(Collectors.toList());

            //再查找出它们的完整信息
            if(targetItemIds.size() == 0){
                //没有目标元素，所以返回空列表即可
                itemQueryListVO.setTotal(0);
                itemQueryListVO.setItemInfoModelList(new LinkedList<>());
                return itemQueryListVO;
            }

            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper
                    .lambda()
                    .in(Item::getItemId,targetItemIds);

            //分页，转换
            Page<Item> page = new Page<>(pageNum,pageSize);
            List<Item> itemList = Optional.ofNullable(this.baseMapper.selectPage(page, itemQueryWrapper).getRecords()).orElse(new LinkedList<>());

            List<ItemInfoModel> itemInfoModelList = itemMapStruct.itemListToItemInfoModelList(itemList);

            itemQueryListVO.setTotal(Optional.ofNullable(this.baseMapper.selectCount(itemQueryWrapper)).orElse(0));
            itemQueryListVO.setItemInfoModelList(itemInfoModelList);

            return itemQueryListVO;
        }
        return itemQueryListVO;
    }

    /**
     * 用户申请加入项目
     * @param itemId
     * @param userId
     */
    @Override
    public void applyInItem(Long itemId, Long userId) {
        if(ObjectUtil.isNull(itemId) || ObjectUtil.isNull(userId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        //查看用户是否在申请中了,并记录申请时间，2小时内不允许重复申请
        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(4);

        String key = String.valueOf(itemId);
        String userIdStr = String.valueOf(userId);
        String lastDatetimeStr = Optional.ofNullable(redisTemplate.<String, String>opsForHash().get(key, userIdStr)).orElse("");

        LocalDateTime lastDatetime = null;
        if(StrUtil.isNotBlank(lastDatetimeStr)){
            lastDatetime = LocalDateTime.parse(lastDatetimeStr);
        }

        if(lastDatetime!=null && lastDatetime.plusHours(2L).isAfter(LocalDateTime.now())){
            throw new MyException(MyExceptionEnum.DATETIME_NOT_MORE_THAN_2HOUR);
        }

        //查看是否有该项目该用户的申请记录，有则先删除旧纪录，再添加新纪录
        if(redisTemplate.opsForHash().hasKey(key,userIdStr)){
            redisTemplate.opsForHash().delete(key,userIdStr);
        }

        redisTemplate.opsForHash().put(key,userIdStr,LocalDateTime.now().toString());
    }

    /**
     * 管理员查看申请列表
     * @param itemId
     * @param userId
     * @return
     */
    @Override
    public ItemApplyInfoVO getItemApplyList(Long itemId, Long userId) {
        if(ObjectUtil.isNull(itemId) || ObjectUtil.isNull(userId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        Item dbItem = Optional.ofNullable(getById(itemId)).orElse(null);
        if(ObjectUtil.isEmpty(dbItem)){
            throw new MyException(MyExceptionEnum.DATA_DOES_NOT_EXIST);
        }

        if(dbItem.getManagerId().compareTo(userId)!=0){
            throw new MyException(MyExceptionEnum.ITEM_MANAGER_EXCEPTION);
        }

        ItemApplyInfoVO itemApplyInfoVO = new ItemApplyInfoVO();
        itemApplyInfoVO.setItemId(itemId);
        itemApplyInfoVO.setItemName(dbItem.getItemName());

        RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(4);

        String key = String.valueOf(itemId);

        Map<String, String> map = redisTemplate.<String, String>opsForHash().entries(key);

        List<UserInfoVO> userInfoVOList = new LinkedList<>();
        map.forEach(
                (k,v) ->{
                    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                    userQueryWrapper.lambda().eq(User::getUserId, k);

                    userInfoVOList.add(userMapStruct.userToUserInfoVO(Optional.ofNullable(userMapper.selectOne(userQueryWrapper)).orElse(new User())));
                }
        );
        itemApplyInfoVO.setUserInfoVOList(userInfoVOList);

        return itemApplyInfoVO;
    }

    /**
     * 获取近day天的个人任务、缺陷统计数据
     * @param personalStaticsDTO
     * @return
     */
    @Override
    public List<PersonalTaskVO> getPersonalStaticsCondition(PersonalStaticsDTO personalStaticsDTO) {
        Long itemId = personalStaticsDTO.getItemId();
        Long userId = personalStaticsDTO.getUserId();
        Integer day = personalStaticsDTO.getDay();

        //获取今天之前所有日期的集合
        List<LocalDate> dateList = getDateList(day);

        List<PersonalTaskVO> personalTaskVOList = new LinkedList<>();
        dateList.forEach(
                date -> {
                    PersonalTaskVO personalTaskVO = new PersonalTaskVO();
                    personalTaskVO.setToday(date);
                    for (int i = 1; i <= 6; i++) {
                        statistics(personalTaskVO,date,itemId,userId,i);
                    }

                    personalTaskVOList.add(personalTaskVO);
                }
        );

        return personalTaskVOList;
    }

    /**
     * 获取相关统计数据【整个项目】
     * @param itemId
     * @return
     */
    @Override
    public PersonalTaskVO getItemStaticsCondition(Long itemId) {
        if(ObjectUtil.isNull(itemId)){
            throw new MyException(MyExceptionEnum.ID_IS_NULL);
        }

        RedisTemplate<String, Object> redisTemplateByTask = redisConfig.getRedisTemplateByDb(1);
        RedisTemplate<String, Object> redisTemplateByBug = redisConfig.getRedisTemplateByDb(2);
        Item item = getById(itemId);

        PersonalTaskVO personalTaskVO = new PersonalTaskVO();
        personalTaskVO.setToday(LocalDate.now());

        personalTaskVO.setUnfinishedTaskCount(Integer.valueOf(String.valueOf(redisTemplateByTask.opsForSet().size(item.getTaskOneId()))));
        personalTaskVO.setProcessingTaskCount(Integer.valueOf(String.valueOf(redisTemplateByTask.opsForSet().size(item.getTaskTwoId()))));
        personalTaskVO.setCompletedTaskCount(Integer.valueOf(String.valueOf(redisTemplateByTask.opsForSet().size(item.getTaskThreeId()))));

        personalTaskVO.setUnfinishedBugCount(Integer.valueOf(String.valueOf(redisTemplateByBug.opsForSet().size(item.getBugOneId()))));
        personalTaskVO.setProcessingBugCount(Integer.valueOf(String.valueOf(redisTemplateByBug.opsForSet().size(item.getBugTwoId()))));
        personalTaskVO.setCompletedBugCount(Integer.valueOf(String.valueOf(redisTemplateByBug.opsForSet().size(item.getBugThreeId()))));

        return personalTaskVO;
    }

    //统计处理时间为当天的数据内容
    private void statistics(PersonalTaskVO personalTaskVO, LocalDate date, Long itemId, Long userId,int method) {
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        LocalTime begin = LocalTime.MIN;
        LocalTime end = LocalTime.MAX;
        taskQueryWrapper.lambda()
                .eq(Task::getItemId,itemId)
                .eq(Task::getReceiveId,userId)
                .eq(Task::getSolveStatus,method)
                .between(Task::getSolveTime,LocalDateTime.of(date,begin),LocalDateTime.of(date,end));

        QueryWrapper<Bug> bugQueryWrapper = new QueryWrapper<>();
        bugQueryWrapper.lambda()
                .eq(Bug::getItemId,itemId)
                .eq(Bug::getReceiveId,userId)
                .eq(Bug::getSolveStatus,method-3)
                .between(Bug::getSolveTime,LocalDateTime.of(date,begin),LocalDateTime.of(date,end));

        if(method == 1){
            personalTaskVO.setUnfinishedTaskCount(Optional.ofNullable(taskMapper.selectCount(taskQueryWrapper)).orElse(0));
        }else if(method == 2){
            personalTaskVO.setProcessingTaskCount(Optional.ofNullable(taskMapper.selectCount(taskQueryWrapper)).orElse(0));
        }else if(method == 3){
            personalTaskVO.setCompletedTaskCount(Optional.ofNullable(taskMapper.selectCount(taskQueryWrapper)).orElse(0));
        }else if(method == 4){
            personalTaskVO.setUnfinishedBugCount(Optional.ofNullable(bugMapper.selectCount(bugQueryWrapper)).orElse(0));
        }else if(method == 5){
            personalTaskVO.setProcessingBugCount(Optional.ofNullable(bugMapper.selectCount(bugQueryWrapper)).orElse(0));
        }else if(method == 6){
            personalTaskVO.setCompletedBugCount(Optional.ofNullable(bugMapper.selectCount(bugQueryWrapper)).orElse(0));
        }
    }

    private List<LocalDate> getDateList(Integer day) {
        LocalDate today = LocalDate.now();
        LocalDate beginDay = today.plusDays(-day);

        long numOfDays = ChronoUnit.DAYS.between(beginDay,today);
        return Stream.iterate(beginDay, date -> date.plusDays(1)).limit(numOfDays).collect(Collectors.toList());
    }

    //获取项目信息列表
    private List<Item> getItemListInfoByItemIds(List<Long> itemIds){
        if(itemIds.isEmpty())
            return new LinkedList<>();

        return this.listByIds(itemIds);
    }

    //筛选分页操作封装
    private ItemQueryListVO packageData(List<ItemInfoModel> itemInfoModelList,String condition,Integer pageNum,Integer pageSize){
        ItemQueryListVO itemQueryListVO = new ItemQueryListVO();

        //筛选，分页
        List<ItemInfoModel> finalModelList = itemInfoModelList
                .stream()
                .filter(itemInfoModel ->
                        itemInfoModel.getItemName().contains(condition)
                                ||
                                itemInfoModel.getManagerName().contains(condition)
                                ||
                                itemInfoModel.getCreateBy().contains(condition)
                )
                .collect(Collectors.toList());

        itemQueryListVO.setTotal(finalModelList.size());
        itemQueryListVO.setItemInfoModelList(finalModelList.stream().skip((pageNum-1)*pageSize).limit(pageSize).collect(Collectors.toList()));

        return itemQueryListVO;
    }

    /**
     * 查找项目任务、缺陷的具体处理情况(策略模式)
     *
     * @param itemId    项目id
     * @param itemInfoDetailModel   细节实体，字段赋予
     * @param method    策略：1未完成的任务 2处理中的任务 3已完成的任务 4未处理的缺陷 5处理中的缺陷 6已处理的缺陷
     */
    private void packageItemDetail(Long itemId,ItemInfoDetailModel itemInfoDetailModel,int method){
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Bug> bugQueryWrapper = new QueryWrapper<>();

        taskQueryWrapper.lambda().eq(Task::getItemId,itemId);
        bugQueryWrapper.lambda().eq(Bug::getItemId,itemId);

        taskQueryWrapper.lambda().eq(Task::getSolveStatus,method);
        bugQueryWrapper.lambda().eq(Bug::getSolveStatus,method-3);

        Integer taskCount = Optional.ofNullable(taskMapper.selectCount(taskQueryWrapper)).orElse(0);
        Integer bugCount = Optional.ofNullable(bugMapper.selectCount(bugQueryWrapper)).orElse(0);

        if(method == 1){
            itemInfoDetailModel.setUnfinishedTaskCount(taskCount);
        }else if(method == 2){
            itemInfoDetailModel.setProcessingTaskCount(taskCount);
        }else if(method == 3){
            itemInfoDetailModel.setCompletedTaskCount(taskCount);
        }else if(method == 4){
            itemInfoDetailModel.setUnfinishedBugCount(bugCount);
        }else if(method == 5){
            itemInfoDetailModel.setProcessingBugCount(bugCount);
        }else if(method == 6){
            itemInfoDetailModel.setCompletedBugCount(bugCount);
        }
    }


    //检查是否是纯数字
    private boolean checkIsNumber(String condition) {
        //不支持超过19位的ID搜索
        if(condition.length()>19){
            return false;
        }else if(condition.length() == 19 && condition.charAt(0) == '9'){
            return false;
        }

        for (int i = 0; i < condition.length(); i++) {
            if(condition.charAt(i) < '0' || condition.charAt(i) > '9'){
                return false;
            }
        }

        return true;
    }

    private void packageItemRedis(Item item){
        Long itemId = item.getItemId();

        item.setTaskOneId(itemId+"-1");
        item.setTaskTwoId(itemId+"-2");
        item.setTaskThreeId(itemId+"-3");

        item.setBugOneId(itemId+"-1");
        item.setBugTwoId(itemId+"-2");
        item.setBugThreeId(itemId+"-3");

        this.baseMapper.updateById(item);
    }
}




